package com.py.korona.db.model.base;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;

public abstract class Entity {
    public static EntityDescription entityDescription() throws Exception {
        throw new Exception("unimplemented method");
    }

    public static String entityTableName() throws Exception {
        throw new Exception("unimplemented method");
    }

    public static String uriAuthority() throws Exception {
        throw new Exception("unimplemented method");
    }

    public static String uriBasePath() throws Exception {
        throw new Exception("unimplemented method");
    }
    protected Long            _id = Long.MIN_VALUE;
    protected ContentResolver contentResolver;
    protected Cursor          cursor;
    protected Uri             uri;

    public Entity() {
        _id = null;
        invalidate();
    }

    public Entity(ContentResolver contentResolver) {
        this();
        this.contentResolver = contentResolver;
    }

    public Entity(ContentResolver contentResolver, Cursor cursor) {
        this(contentResolver);
        this.setCursor(cursor);
    }

    public Entity(ContentResolver contentResolver, Uri uri) {
        this(contentResolver);
        this.uri = uri;
    }

    public Long get_id() {
        return _id;
    }

    public void invalidate() {
    }

    public void removeFromDatabase() {
        if (null != uri) {
            contentResolver.delete(uri, null, null);
        }
    }

    public void save() throws UnsupportedOperationException, NullPointerException {
        if (null != uri) {
            contentResolver.update(uri, contentValues(), null, null);
        } else {
            Uri contentUri = this.objectsListUri();
            Uri entityUri = contentResolver.insert(contentUri, contentValues());
            String idValue = entityUri.getQueryParameter("_id");
            this.set_id(Long.valueOf(idValue));
        }
    }

    public void set_id(Long _id) {
        this._id = _id;
    }

    public void updateWithContentValues(ContentValues contentValues) {
    }

    protected abstract ContentValues contentValues();

    protected abstract Uri objectsListUri();

    protected abstract void onDataChanged(Cursor cursor);

    protected void setCursor(Cursor cursor) {
        this.cursor = cursor;
        if (cursor.moveToFirst()) {
            onDataChanged(cursor);
        }
        cursor.close();
    }
}
